//
//  HQNetRequestTool.m
//  WenDuEducation
//
//  Created by 黄华强 on 2017/8/1.
//  Copyright © 2017年 黄华强. All rights reserved.
//

#import "HQNetRequestTool.h"
#import <AFNetworking.h>
#import <AFNetworking/UIImageView+AFNetworking.h>
#import <UIKit+AFNetworking.h>
#import "HQNetworkConst.h"
//#import <QiniuSDK.h>

//请求类型枚举
typedef enum : NSUInteger {
    GETRequest = 0,
    POSTFormRequest,
    POSTJSONRequest,
} RequestType;

@interface HQNetRequestTool ()

@property (nonatomic, strong)  UILabel *networkLabel;

@end


@implementation HQNetRequestTool


+ (instancetype)sharedHQNetRequestTool {
    
    static HQNetRequestTool *instance = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        instance = [HQNetRequestTool new];
    });
    
    return instance;
}



#pragma 监测网络的可链接性
- (BOOL) netWorkReachabilityWithURLString:(NSString *) strUrl {
    
    __block BOOL netState = NO;
    
    NSURL *baseURL = [NSURL URLWithString:strUrl];
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
    
    NSOperationQueue *operationQueue = manager.operationQueue;
    
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                //取消挂起
                [operationQueue setSuspended:NO];
                netState = YES;
                break;
            case AFNetworkReachabilityStatusNotReachable:
                netState = NO;
            default:
                //挂起
                [operationQueue setSuspended:YES];
                break;
        }
        
        self.netWorkCanUse = netState;
        
        if (netState) {
            
            self.networkLabel.text = HQNetworkLocalizedString(HQNetRequestTool_networkConnect);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.networkLabel.hidden = YES;
            });
            
        } else {
            self.networkLabel.hidden = NO;
            self.networkLabel.text = HQNetworkLocalizedString(HQNetRequestTool_networkDisconnect);
            
        }
        
    }];
    
    [manager.reachabilityManager startMonitoring];
    
    return netState;
}

//断网 提示框懒加载
- (UILabel *)networkLabel {
    
    if (!_networkLabel) {
        
        _networkLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 60, [UIScreen mainScreen].bounds.size.width - 60, 30)];
        _networkLabel.textAlignment = NSTextAlignmentCenter;
        _networkLabel.textColor = [UIColor whiteColor];
        _networkLabel.backgroundColor = [UIColor blackColor];
        _networkLabel.alpha = 0.7;
        _networkLabel.layer.masksToBounds = YES;
        _networkLabel.layer.cornerRadius = 5;
        _networkLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
        _networkLabel.hidden = YES;
        
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:_networkLabel];
    }
    
    return _networkLabel;
}


//处理网络回调

+ (void)processing:(id)responseObject withValueBlock:(ReturnValueBlock)valueBlock {
    
    NSError *error = nil;
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
    
    if (!error) {
        
        if (valueBlock) {
            
            /*处理token异常*/
            if (jsonDic[@"status"] && ![jsonDic[@"status"] isKindOfClass:[NSNull class]] && [jsonDic[@"status"] intValue] == 401) {
                [HQAlert hideHUD];
                
                [HQAlert showMessage:jsonDic[@"msg"]];
                
//                [LRTUserInfo cleanUerInfo];
//
//                LRTLoginController *loginVC = [LRTLoginController new];
//
//                loginVC.hidesBottomBarWhenPushed = YES;
//
//                LRTBaseNaviController *naviVC = [[LRTBaseNaviController alloc] initWithRootViewController:loginVC];
//
//                [[HQAlert getCurrentViewController] presentViewController:naviVC animated:YES completion:nil];
                
                
            } else if (jsonDic[@"status"] && ![jsonDic[@"status"] isKindOfClass:[NSNull class]] && [jsonDic[@"status"] intValue] == 400) {
                
                [HQAlert hideHUD];
                
            }
            
            
            valueBlock(jsonDic);
        }
        
    } else {
        
        if (valueBlock) {
            NSData *data = (NSData *)responseObject;
            NSString *retunString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            
            valueBlock(retunString);
        }
        
    }
    
}

#pragma mark - GET请求
+ (void) GETRequestURLString: (NSString *) requestURLString
                  parameter: (NSDictionary *) parameter
                 valeuBlock: (ReturnValueBlock) valueBlock
                 errorBlock: (ErrorCodeBlock) errorBlock {
    
    [HQNetRequestTool requestWithType:GETRequest
                       URLString:requestURLString
                       parameter:parameter
                       valeuBlock:valueBlock
                       errorBlock:errorBlock];
}

#pragma mark - POST表单请求
+ (void) POSTFormRequestURLString: (NSString *) requestURLString
                       parameter: (NSDictionary *) parameter
                      valeuBlock: (ReturnValueBlock) valueBlock
                      errorBlock: (ErrorCodeBlock) errorBlock {
    
    [HQNetRequestTool requestWithType:POSTFormRequest
                        URLString:requestURLString
                        parameter:parameter
                        valeuBlock:valueBlock
                        errorBlock:errorBlock];
}

#pragma mark - POST JSON请求
+ (void) POSTJSONRequestURLString: (NSString *) requestURLString
                        parameter: (NSDictionary *) parameter
                       valeuBlock: (ReturnValueBlock) valueBlock
                       errorBlock: (ErrorCodeBlock) errorBlock {
    
    [HQNetRequestTool requestWithType:POSTJSONRequest
                        URLString:requestURLString
                        parameter:parameter
                        valeuBlock:valueBlock
                        errorBlock:errorBlock];
}


+ (void) requestWithType: (RequestType) requestType
              URLString: (NSString *) requestURLString
              parameter: (NSDictionary *) parameter
             valeuBlock: (ReturnValueBlock) valueBlock
              errorBlock: (ErrorCodeBlock) errorBlock {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
   // [manager.requestSerializer setValue:[LRTUserInfo UserInfo].access_token forHTTPHeaderField:@"access-token"];
    [manager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"deviceType"];
   // [manager.requestSerializer setValue:APP_VERSION forHTTPHeaderField:@"appVersionName"];
    
    NSTimeZone *zone = [NSTimeZone localTimeZone];
    // 获取指定时区的名称
    NSString *strZoneName = [zone name];
    [manager.requestSerializer setValue:strZoneName forHTTPHeaderField:@"timeZone"];
    
    switch (requestType) {
            
        case GETRequest:
        {
            [manager GET:requestURLString parameters:parameter progress:^(NSProgress * _Nonnull downloadProgress) {
                //下载进度
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
               
                //成功回调后调用处理数据方法
                [HQNetRequestTool processing:responseObject withValueBlock:valueBlock];
                [manager.session finishTasksAndInvalidate];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                
                if (errorBlock) {
                    errorBlock(error);
                }
                [manager.session finishTasksAndInvalidate];
                
            }];
        }
            break;
        case POSTFormRequest:
        {
            [manager POST:requestURLString parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
                //上传进度
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                //成功回调后调用处理数据方法
                [HQNetRequestTool processing:responseObject withValueBlock:valueBlock];
                [manager.session finishTasksAndInvalidate];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

                if (errorBlock) {
                    errorBlock(error);
                }
                [manager.session finishTasksAndInvalidate];
            }];
        }
            break;
        case POSTJSONRequest:
        {
            //JSON提交单独处理字符串
            [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError * __autoreleasing * error) {
                
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:error];
                NSString *argString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                
                return argString;
            }];
            
            
            [manager POST:requestURLString parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
                //上传进度
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                //成功回调后调用处理数据方法
                [HQNetRequestTool processing:responseObject withValueBlock:valueBlock];
                [manager.session finishTasksAndInvalidate];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                if (errorBlock) {
                    errorBlock(error);
                }
                [manager.session finishTasksAndInvalidate];
            }];
        }
            break;
        default:
            break;
            
    }
    
    
}

+ (void)requestWithImageDictArray: (NSArray<NSDictionary<NSString *,UIImage *> *> *) dataDictArr
                 requestURLString: (NSString *) requestURLString
                        parameter: (NSDictionary *) parameter
                       valeuBlock: (ReturnValueBlock) valueBlock
                       errorBlock: (ErrorCodeBlock) errorBlock {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
  //  [manager.requestSerializer setValue:[LRTUserInfo UserInfo].access_token forHTTPHeaderField:@"access-token"];
    [manager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"deviceType"];
    // [manager.requestSerializer setValue:APP_VERSION forHTTPHeaderField:@"appVersionName"];
    
    NSTimeZone *zone = [NSTimeZone localTimeZone];
    // 获取指定时区的名称
    NSString *strZoneName = [zone name];
    [manager.requestSerializer setValue:strZoneName forHTTPHeaderField:@"timeZone"];
    
    [manager POST:requestURLString parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //将图片添加到formData
        for (NSInteger index = 0; index < dataDictArr.count; index ++) {
            NSDictionary<NSString *,UIImage *> *dict = dataDictArr[index];
            
            [dict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, UIImage * _Nonnull obj, BOOL * _Nonnull stop) {
                
                UIImage *image = obj;
                NSData *imageData = UIImageJPEGRepresentation(image, 1);
                
                // 设置时间格式
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                [formatter setDateFormat:@"yyyyMMddHHmmss"];
                NSString *dateString = [formatter stringFromDate:[NSDate date]];
                
                NSString *fileName = [NSString  stringWithFormat:@"%@%@.jpg", key,dateString];
                
                [formData appendPartWithFileData:imageData name:key fileName:fileName mimeType:@"image/jpeg"];
                
            }];
            
            
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功回调后调用处理数据方法
        [HQNetRequestTool processing:responseObject withValueBlock:valueBlock];
        [manager.session finishTasksAndInvalidate];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        if (errorBlock) {
            errorBlock(error);
        }
        
        [manager.session finishTasksAndInvalidate];
    }];
    
}



@end
